<?php
namespace App\Http\Controllers;
use \App\Product;
use \App\ProductType;

class ProductController extends Controller{
    /**
     * 展示通讯录
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function setting(Product $product){

        return view('admin.test.product',compact('product'));
    }
    public function index()
    {
        return view('admin.product.index');
    }
    /**
     * 数据接口
     */
    public function data()
    {
        $count=Product::count();
        if ($count>0) {
            if(isset($_GET['key']) && $_GET['key']['id']!="") {
                $key= $_GET['key']['id'];//搜索序列号
                $users = Product::where(['id' => $key])->get();
            }
            else{
                $page = $_GET['page']; //当前页数
                $limit = $_GET['limit']; //每页的数量
                $page_count = ($page - 1) * $limit;

                $users = Product::orderBy('created_at', 'desc')->offset($page_count)->limit($limit)->with('type')->get();
                for($i=0;$i<$count;$i++)
                {
                    $users[$i]['type_id']=$users[$i]['type']['name'];
                }

            }
            return json_encode(
                [
                    "code" => 0,
                    'msg' => '',
                    'count' => $count,
                    'data' => $users
                ]
            );
        } else{
            return [
                'code'=>0,
                "msg"=>"",
                "count"=>0,
                "data"=>[]
            ];
        }
    }
    /**
     * 添加界面
     */
    public function product_create(){
        return view('admin.product.product_create');
    }
    public function product_store(){
        ProductType::create($_REQUEST);
        return "<script> window.parent.location.reload();</script>";
    }
    public function create(){
        $types=ProductType::get();

        //print_r($types);die;
        return view('admin.product.create',compact('types'));
    }
    /**
     *
     */
    public function operation(){
        $param=$_POST;
        //print_r($param);die;
        //$filds=$this->array_hebing($param,'describe','product_name','specifications','image');//传入需要更新的字段
        //$user=Product::where('id', $param['id'])->update($filds); //创建字段
        //渲染
        //echo '<script>alert("更新成功");</script>';
        Product::create($param);
        return redirect("/admin/product");
    }
    /**
     * 添加操作逻辑简单实现
     */
    public function store(){
        $param=$_POST;
        $param['image']=$param['image'];
        //print_r($param);die;
        $filds=$this->array_hebing($param,'describe','product_name','type_id','specifications','cost_price','retail_price','image','Remake');//传入需要更新的字段
        Product::where('id', $param['id'])->update($filds); //创建字段
        //渲染
        //echo '<script>alert("更新成功");</script>';
        return redirect("/admin/product");
    }
    /*
     * 删除
     */
    public function delete($id)
    {
        AdminUser::where('id', '=', $id)->delete();
        return back();
    }
    public function edit($id){

        $users = Product::orderBy('created_at', 'desc')->where('id',"=",$id)->with('type')->first();
        $users['type_name']=$users['type']['name'];
        //print_r($users);die;
        $types=ProductType::get();
        //print_r($type[0]['name']);die;
        //
        return view('admin.product.update',compact('users','types'));
    }
    public function update(){
      $filds=$this->array_hebing($_REQUEST,'describe','product_name','specifications');//传入需要更新的字段
      if(empty($filds))  //判断数据是否为空 是则不修改
      {
          return ['statu'=>'0'];
      }
      else{
          Product::where('id', $_REQUEST['id'])->update($filds);
          return ['statu'=>'200'];
      }

    }
    public function showMsg($status,$message = '',$data = array()){

        $result = array(
            'status' => $status,
            'message' =>$message,
            'data' =>$data
        );
        exit( json_encode($result));
    }
    public function upload(){

        if ($_FILES) {
            //上传图片具体操作
            $file_name = $_FILES['file']['name'];
            //$file_type = $_FILES["file"]["type"];
            $file_tmp = $_FILES["file"]["tmp_name"];
            $file_error = $_FILES["file"]["error"];
            $file_size = $_FILES["file"]["size"];
            if ($file_error > 0) { // 出错
                $message = $file_error;
            } elseif($file_size > 1048576) { // 文件太大了
                $message = "上传文件不能大于1MB";
            }else{
                $date = date('Ymd');
                $file_name_arr = explode('.', $file_name);
                $new_file_name = date('YmdHis') . '.' . $file_name_arr[1];

                $path = base_path()."/public/upload/".$date."/";
                $file_path = $path . $new_file_name;

                if (file_exists($file_path)) {
                    $message = "此文件已经存在啦";
                } else {
                    //TODO 判断当前的目录是否存在，若不存在就新建一个!
                    if (!is_dir($path)){
                        mkdir($path,0777);
                    }
                    $upload_result = move_uploaded_file($file_tmp, $file_path);
                    //此函数只支持 HTTP POST 上传的文件
                    if ($upload_result) {
                        $status = 1;
                        $message = $file_path;
                        $return_file="/upload/".$date."/".$new_file_name;
                    } else {
                        $message = "文件上传失败，请稍后再尝试";
                        $return_file="文件上传失败，请稍后再尝试";
                    }
                }
            }
        } else {
            $message = "参数错误";
        }

        return $this->showMsg($status, $return_file);
    }
    /**
     * //组成一个我所要的数组用于数据库更新 并且
     * @param array ...$numbers 传进去的字段
     * @return array /￥/返回一个键=字段 值=数值的数组
     */
    public function array_hebing($Data,...$numbers){
      //  print_r($Data);die;

        $data=Product::where('id', $Data['id'])->first();
        //print_r($_REQUEST);die;
        $filds=[];
        if($Data && is_array($Data)){   //组成一个我所要的数组用于数据库更新
            //print_r($_REQUEST);die;
            foreach($numbers as $fild){
                foreach ($Data as $key=> $value){
                    if($fild==$key)
                    {
                            $filds[$fild] = $value;
                            continue;
                    }
                }
            }
            $start=0;  //循环记数
            foreach($filds as $key=>$value)  //删除请求更新字段中没有修改的字段
            {
                if($data[$key]==$filds[$key]) {   //判断是否相同 相同则从需要更新的数组中删除该键值
                        array_splice($filds, $start, 1);
                        $start=$start-1;
                }
                $start=$start+1;
            }
        }
        return $filds;
    }
}